#!/bin/bash

. $LKP_SRC/lib/http.sh
. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/debug.sh

config_env_repos()
{
	rm -rf /etc/yum.repos.d.bak
	mv /etc/yum.repos.d /etc/yum.repos.d.bak
	mkdir -p /etc/yum.repos.d
	local my_repo="/etc/yum.repos.d/my.repo"
	i=1
	for repo in ${env_repos[@]}
	do
		cat >> ${my_repo} <<-EOF
		[my_repo_$i]
		name=my_repo_$i
		baseurl=${repo}
		enabled=1
		gpgcheck=0
		priority=$i

		EOF
		let i=i+1
	done
}

init_env()
{
	config_env_repos
	yum install -y findutils cpio 'dnf-command(download)'
}

config_customs_repos()
{
	rm -rf /etc/yum.repos.d.bak
	mv /etc/yum.repos.d /etc/yum.repos.d.bak
	mkdir -p /etc/yum.repos.d
	local my_repo="/etc/yum.repos.d/my.repo"
	i=1
	for repo in ${custom_repos[@]}
	do
		cat >> ${my_repo} <<-EOF
		[my_repo_$i]
		name=my_repo_$i
		baseurl=${repo}
		enabled=1
		gpgcheck=0
		priority=$i

		EOF
		let i=i+1
	done
}

tailor_image()
{
	tailor_dir=/home/tailor
	initrd_dir=${tailor_dir}/initrd
	result_dir=${tailor_dir}/result
	mkdir -p ${result_dir}
	config_customs_repos
	yum download busybox --downloadonly --downloaddir=/tmp || die "yum download busybox fail."
	cd /tmp
	rpm2cpio busybox-*.rpm | cpio -div
	mkdir -p ${initrd_dir}
	cp -rf sbin ${initrd_dir}

	cd ${initrd_dir}
	local dirs=(dev mnt root sys usr bin etc lib proc tmp var)
	for dir in ${dirs[@]}
	do
		mkdir ${dir}
	done
	./sbin/busybox --install ./bin

	cat > init <<-EOF
	#!/bin/sh

	mount -t proc none /proc
	mount -t sysfs none /sys

	cat <<!
	                         ______      _           
	                        |  ____|    | |          
	   ___  _ __   ___ _ __ | |__  _   _| | ___ _ __ 
	  / _ \| '_ \ / _ \ '_ \|  __|| | | | |/ _ \ '__|
	 | (_) | |_) |  __/ | | | |___| |_| | |  __/ |   
	  \___/| .__/ \___|_| |_|______\__,_|_|\___|_|   
	       | |                                       
	       |_|                                      
	
	Welcome to openEuler
	
	!
	
	#setsid cttyhack sh
	exec /bin/sh +m
	EOF
	chmod a+x init
	find . -print0 | cpio --null -ov --format=newc | gzip -9 > ${result_dir}/initramfs.cpio.gz

}

upload_result()
{
	for one in $(ls ${result_dir})
	do
		upload_one_curl ${result_dir}/${one} ${upload_image_dir} || die "upload ${result_dir}/${one} to ${upload_image_dir} error"
	done
}

check_build_result()
{
	res=$(find "$result_dir" -type f -name "*cpio*")
	[ -z "$res" ] && die "can't find the cpio result"
	[ "$?" != "0" ] && exit 0
}

init_env
config_env_repos
tailor_image
upload_result
check_build_result
